/*
 * Copyright (c) 2019, Zhejiang uniview Technologies Co., Ltd. All rights reserved.
 * <http://www.uniview.com/>
 *------------------------------------------------------------------------------
 * Product     :
 * Module Name :
 * Date Created: 2020-04-07 10:42
 * Creator     : s04180
 * Description :
 *
 *------------------------------------------------------------------------------
 * Modification History
 * DATE        NAME             DESCRIPTION
 *------------------------------------------------------------------------------
 *
 *------------------------------------------------------------------------------
 */
package com.kyg.tjtoolmanager.net.netty.manager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.kyg.tjtoolmanager.App;
import com.kyg.tjtoolmanager.db.SQLiteUtils;
import com.kyg.tjtoolmanager.net.netty.constant.LapiUriConstat;
import com.kyg.tjtoolmanager.utils.Utils;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.util.internal.StringUtil;

import java.util.Map;
import java.util.Objects;

/**
 * HttpConnectionThread
 * <p>
 * 创建订阅，每个门禁都需要订阅
 *
 * @author s04180
 * @Description
 */
public class RequestSubscriptionThread extends Thread {

    //终端接口地址URI
    private String api = LapiUriConstat.EVENT_SUBSCRIPTION;

    //终端设备的序列号 or  响应心跳的 deviceCode
    //210235C6LC323C000074
    //210235C3R0319B000026
    private String serialNo = "";

    //请求的接口参数
    private String json = "";

    public void setSerialNo(String serialNo) {
        this.serialNo = serialNo;
    }

    @Override
    public void run() {
        try {
            if (!StringUtil.isNullOrEmpty(serialNo)) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("AddressType", 0);
                jsonObject.put("IPAddress", Utils.getLocalIP());
                jsonObject.put("Port", Integer.parseInt(App.globalVal.nettyPort) + 1);
                jsonObject.put("Duration", 4294967295l);
                jsonObject.put("Type", 255);
                json = jsonObject.toJSONString();
                FullHttpRequest httpRequest = null;
                httpRequest = RequestDeviceManager.createRequestDeviceInfo(api, json, HttpMethod.POST);

                /**
                 *
                 */
                Map<String, String> map = HttpKeepAliveManager.getResponseMapByKeepAliveConnection(serialNo, httpRequest);
                if (Objects.nonNull(map)) {
                    SQLiteUtils.insertLog("Subscription:{" + serialNo + " Response Info:\n" + JSON.toJSONString(map, SerializerFeature.PrettyFormat));
                } else {
                    SQLiteUtils.insertLog("... ... 请求超时 ... ... ");
                }
            }
        } catch (Exception e) {
//            SQLiteUtils.insertLog("{}" + e.getMessage());
        }
    }
}
